﻿Imports System.Data.SqlClient
Public Class DbConnect
    Private conn As SqlConnection
    Private conStr As String
    Public Sub New()
        conn = New SqlConnection
    End Sub
    Public Function Connect(ByVal server As String, ByVal database As String) As Boolean
        conStr = "server=" + server + ";database=" + database + ";integrated security=true"
        Try
            conn.ConnectionString = conStr
            conn.Open()
            Return True
        Catch ex As Exception
            'Throw New Exception("Không thể kết nối tới CSDL")
            Return False
        End Try
    End Function
    Public Function Connect(ByVal server As String, ByVal database As String, ByVal uid As String, ByVal pwd As String)
        conStr = "server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd
        Try
            conn.ConnectionString = conStr
            conn.Open()
            Return True
        Catch ex As Exception
            'Throw New Exception("Không thể kết nối tới CSDL")
            Return False
        End Try
    End Function
    Public Function QueryTable(ByVal queryStr As String) As DataTable
        Dim adapter As New SqlDataAdapter(queryStr, conn)
        Dim dt As New DataTable
        adapter.Fill(dt)
        Return dt
    End Function
    Public Function Query(ByVal queryStr As String) As Boolean
        Dim comm As New SqlCommand(queryStr, conn)
        If conn.State <> ConnectionState.Open then conn.Open
        'Try
        comm.ExecuteNonQuery()
        Return True

        'Catch ex As Exception
        '    Return False
        'End Try
    End Function
    Public Function CloseConnection() As Boolean
        Try
            conn.Close()
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function
    Public Function IsConnected() As Boolean
        Return conn.State=ConnectionState.Open
    End Function
End Class
